package com.sws.worktive.sign_up_service;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.widget.Toast;

import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.sws.worktive.job_service.BaseFetcher;
import com.sws.worktive.volley.MyVolley;

public class VerificationCodeFetcher extends BaseFetcher {
	private final String VERIFICATION_CODE_URL_PAR1 = "http://www.worktive.com/api/twilio/index.php/verification/";
	private final String VERIFICATION_CODE_URL_PAR2 = "/7dea6e8128c3c4120aa1016ded6aee9e";
	
	public VerificationCodeFetcher(Context context){
		mContext = context;
	}
	
	public void fetchJobs(String phoneNumber,String requestTag, VerificationCodeReceiveListener receiveListener){
		
		JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
				Method.GET, 
				constructURLWithPhoneNumber(phoneNumber), 
				null, 
				createVerificationCodeFetcherSuccessListener(receiveListener), 
				createVerificationCodeFetcherErrorListener(receiveListener));
		MyVolley.getMyVolley(mContext).addToRequestQueue(jsonObjectRequest, requestTag);
	}
	
	private String constructURLWithPhoneNumber(String phoneNumber){
		StringBuilder stringBuilder= new StringBuilder(VERIFICATION_CODE_URL_PAR1);
		stringBuilder.append(phoneNumber).append(VERIFICATION_CODE_URL_PAR2);
		return stringBuilder.toString();
	}
	
	private Response.Listener<JSONObject> createVerificationCodeFetcherSuccessListener(final VerificationCodeReceiveListener receiveListener){
		return new Response.Listener<JSONObject>() {
			@Override
			public void onResponse(JSONObject jsonObject) {
				try {
					if (!checkStatus(jsonObject)) {
						receiveListener.onVerificationCodeReceived(null);
						return;
					}
					String verificationCode = jsonObject.getString("code");
					receiveListener.onVerificationCodeReceived(verificationCode);
				} catch (JSONException e) {
					e.printStackTrace();
					Toast.makeText(mContext, mContext.getString(com.sws.worktive.R.string.something_went_wrong), Toast.LENGTH_SHORT).show();
					receiveListener.onVerificationCodeReceived(null);
				}
			}
		};
	}
	
	private Response.ErrorListener createVerificationCodeFetcherErrorListener(final VerificationCodeReceiveListener receiveListener) {
		return new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				showErrorMessage(error);
			}
		};
	}
	
	public interface VerificationCodeReceiveListener{
		void onVerificationCodeReceived(String verificationCode);
	}
}
